<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    if (!isset($_GET['path'])) {
        throw new Exception('缺少图片路径参数');
    }
    
    $imagePath = $_GET['path'];
    $fullPath = __DIR__ . '/../../uploads/books/' . $imagePath;
    
    error_log("请求图片路径: path={$imagePath}, fullPath={$fullPath}");
    
    // 安全检查：确保路径在允许的目录内
    $realPath = realpath($fullPath);
    $uploadsDir = realpath(__DIR__ . '/../../uploads/books/');
    
    error_log("实际路径: realPath={$realPath}, uploadsDir={$uploadsDir}");
    
    if (!$realPath || strpos($realPath, $uploadsDir) !== 0) {
        throw new Exception('无效的图片路径');
    }
    
    if (!file_exists($fullPath)) {
        error_log("图片文件不存在: {$fullPath}");
        // 尝试使用默认封面
        $defaultCover = __DIR__ . '/../../images/default-cover.jpg';
        if (file_exists($defaultCover)) {
            $fullPath = $defaultCover;
            error_log("使用默认封面: {$defaultCover}");
        } else {
            throw new Exception('图片文件不存在，且默认封面也不存在');
        }
    }
    
    // 获取文件MIME类型
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $fullPath);
    finfo_close($finfo);
    
    error_log("图片MIME类型: {$mimeType}");
    
    // 设置响应头
    header('Content-Type: ' . $mimeType);
    header('Cache-Control: public, max-age=86400'); // 24小时缓存
    
    // 输出图片内容
    readfile($fullPath);
    
} catch (Exception $e) {
    error_log('Image Error: ' . $e->getMessage());
    header('Content-Type: application/json');
    http_response_code(404);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?> 